package com.blacktea.cloudgateway.controller;

import com.blacktea.cloudapicommon.beans.CommonResult;
import com.blacktea.cloudgateway.config.RedisRouteDefinitionRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: black tea
 * @date: 2021/8/3 13:27
 */
@RestController
@RequestMapping("/route")
@RequiredArgsConstructor
public class RouteController {

    private final RedisRouteDefinitionRepository redisRouteDefinitionRepository;

    @PostMapping("/add")
    public CommonResult add(@RequestBody List<RouteDefinition> definitions) {
       List<Mono<Void>> saves = new ArrayList<>();
        definitions.forEach(d -> {
            Mono<RouteDefinition> just = Mono.just(d);
            Mono<Void> save = redisRouteDefinitionRepository.save(just);
            saves.add(save);
        });
        return new CommonResult(200,"成功",saves);
    }

    @DeleteMapping("/{id}")
    public CommonResult delete(@PathVariable("id") String id) {
        Mono<String> just = Mono.just(id);
        return new CommonResult(200,"成功",redisRouteDefinitionRepository.delete(just));
    }

    @PostMapping("/update")
    public CommonResult update(@RequestBody List<RouteDefinition> definitions) {
        List<Mono<Void>> saves = new ArrayList<>();
        definitions.forEach(d -> {
           Mono<RouteDefinition> just = Mono.just(d);
           Mono<Void> save = redisRouteDefinitionRepository.save(just);
           saves.add(save);
       });
        return new CommonResult(200,"成功",saves);
    }

}